package com.lalifa.googledate.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.lalifa.extension.DateExtensionKt;
import com.lalifa.googledate.R;
import com.lalifa.googledate.api.AddEvent;
import com.lalifa.googledate.api.DayModel;
import com.lalifa.googledate.api.EventInfo;
import com.lalifa.googledate.api.EventListBean;
import com.lalifa.googledate.api.EventModel;
import com.lalifa.googledate.api.EventPositionBean;
import com.lalifa.googledate.api.MessageEvent;
import com.lalifa.googledate.api.MonthModel;
import com.lalifa.googledate.ui.activity.MainActivity;
import com.lalifa.googledate.util.MonthChangeListener;
import com.lalifa.googledate.util.Tool;
import com.lalifa.utils.LiveDataBus;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.Months;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Objects;

public class GooglecalenderView extends LinearLayout {
    private Context context;
    private ViewPager2 viewPager;
    private MonthChangeListener monthChangeListner;
    private int currentmonth = 0;
    private LocalDate mindate, maxdate;
    private int mDefaultEventColor = Color.parseColor("#9fc6e7");

    public GooglecalenderView(Context context) {
        super(context);
        LayoutInflater.from(context).inflate(R.layout.viewpagerlay, this);
        this.context = context;
    }

    public GooglecalenderView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.viewpagerlay, this);
        this.context = context;


    }

    public GooglecalenderView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        LayoutInflater.from(context).inflate(R.layout.viewpagerlay, this);
        this.context = context;


    }

    public GooglecalenderView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        LayoutInflater.from(context).inflate(R.layout.viewpagerlay, this);
        this.context = context;


    }

    public void setMonthChangeListner(MonthChangeListener monthChangeListner) {
        this.monthChangeListner = monthChangeListner;
    }

    public int calculateCurrentMonth(LocalDate currentmonthda) {
        if (currentmonthda == null || mindate == null) return 0;
        LocalDate mindateobj = mindate.toDateTimeAtStartOfDay().dayOfMonth().withMinimumValue().toLocalDate();
        LocalDate current = currentmonthda.dayOfMonth().withMaximumValue();
        int months = Months.monthsBetween(mindateobj, current).getMonths();
        return months;
    }

    public int getCurrentmonth() {
        return currentmonth;
    }

    public void setCurrentmonth(LocalDate currentmonthda) {
        if (mindate == null) return;
        currentmonth = calculateCurrentMonth(currentmonthda);
        if (viewPager.getCurrentItem() != currentmonth) {
            viewPager.setCurrentItem(currentmonth, false);
            //  viewPager.getAdapter().notifyDataSetChanged();
        }
        updategrid();
    }

    public void setCurrentmonth(int position) {
        currentmonth = position;
        if (viewPager.getCurrentItem() != currentmonth) {
            viewPager.setCurrentItem(currentmonth, false);
            //  viewPager.getAdapter().notifyDataSetChanged();
        }
    }

    public void init(ArrayList<EventListBean> eventhashmap) {
        viewPager = findViewById(R.id.viewpager);
        LocalDate mindate = new LocalDate().minusYears(Tool.minusYears);
        LocalDate maxdate = new LocalDate().plusYears(Tool.plusYears);
        this.mindate = mindate;
        this.maxdate = maxdate;
        DateTime mindateobj = mindate.toDateTimeAtStartOfDay();
        DateTime maxdateobj = maxdate.toDateTimeAtStartOfDay();
        int months = Months.monthsBetween(mindateobj, maxdateobj).getMonths();
        final ArrayList<MonthModel> arrayList = new ArrayList<>();
        ArrayList<EventListBean> eventhash = new ArrayList<>();
        for (int mn = 1; mn <= months; mn++) {
            int firstday = mindateobj.dayOfMonth().withMinimumValue().dayOfWeek().get();
            if (firstday == 7) firstday = 0;
            //int lastDay = mindateobj.dayOfMonth().withMaximumValue().dayOfWeek().get();
            MonthModel month = new MonthModel();
            month.setMonthnamestr(mindateobj.toString("MMMM"));
            month.setMonth(mindateobj.getMonthOfYear());
            month.setNoofday(mindateobj.dayOfMonth().getMaximumValue());
            month.setYear(mindateobj.getYear());
            month.setFirstday(firstday);
            int currentYear = new LocalDate().getYear();
            ArrayList<DayModel> dayModelArrayList = new ArrayList<>();
            DateTime startday = mindateobj.dayOfMonth().withMinimumValue().withTimeAtStartOfDay();
            EventInfo eventInfo1 = new EventInfo();
            eventInfo1.eventtitles = new String[]{"start"};
            //添加月开始视图
            eventhash.add(new EventListBean(startday.toLocalDate(), eventInfo1));
            //添加周视图
            var p = 0;
            var weekPosition = 0;
            for (int j = 0; j < month.getNoofday(); j++) {
                LocalDate minweek = startday.toLocalDate();
                String lastPattern = minweek.getYear() == currentYear ? "MM-dd" : "MM-dd YYYY";
                String week = context.getString(R.string.weekBig);
                if (j == p) {
                    if (minweek.compareTo(startday.dayOfMonth().withMaximumValue().toLocalDate()) < 0) {
                        p += 7;
                        weekPosition++;
                        String[] s = new String[]{"weekView" + week + weekPosition + "(" + minweek.toString("MM-dd") + " - "
                                + minweek.plusDays(7).toString(lastPattern).toUpperCase() + ")"};
                        eventhash.add(new EventListBean(minweek, new EventInfo(s)));
                    }
                }
                //添加事件
                DayModel dayModel = new DayModel();
                dayModel.setDay(startday.getDayOfMonth());
                dayModel.setMonth(startday.getMonthOfYear());
                dayModel.setYear(startday.getYear());
                boolean isTodayHave = false;
                LocalDate now = LocalDate.now();
                if (!eventhashmap.isEmpty()) {
                    for (int k = 0; k < eventhashmap.size(); k++) {
                        if (eventhashmap.get(k).getData().equals(startday.toLocalDate())) {
                            EventInfo eventInfo = eventhashmap.get(k).getEvent();
//                        List<String> list = Arrays.asList(eventInfo.eventtitles);
//                        list = new ArrayList<>(list);
//                        Collections.addAll(list, eventInfo.eventtitles);
//                        String[] mStringArray = new String[list.size()];
//                        eventInfo.eventtitles = list.toArray(mStringArray);
                            EventListBean bean = new EventListBean(startday.toLocalDate(), eventInfo);
                            if (!eventhash.contains(bean)) {
                                eventhash.add(bean);
                            }
                            dayModel.setEventlist(true);
                            dayModel.setEventInfo(bean.getEvent());
                        }
                        if (eventhashmap.get(k).getData().equals(now)) {
                            isTodayHave = true;
                        }
                    }
                }

                if (startday.toLocalDate().equals(new LocalDate())) {
                    dayModel.setToday(true);
                    currentmonth = mn;
                    if (!isTodayHave) {
                        LocalDate todayDate = LocalDate.now();
                        EventInfo info = new EventInfo(new String[]{"today"});
                        eventhash.add(new EventListBean(todayDate, info));
                    }
                } else {
                    dayModel.setToday(false);
                }
                dayModelArrayList.add(dayModel);
//              if (j==month.getNoofday()&&i!=months){
//                  String s[]={"end"};
//                  eventhash.put(startday.toLocalDate(),new EventInfo(s));
//              }
                startday = startday.plusDays(1);
            }
            month.setDayModelArrayList(dayModelArrayList);
            arrayList.add(month);
            mindateobj = mindateobj.plusMonths(1);
        }

        final MonthPagerAdapter myPagerAdapter = new MonthPagerAdapter(context, arrayList);
        viewPager.setAdapter(myPagerAdapter);
        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                MainActivity mainActivity = (MainActivity) context;
                currentmonth = position;
                if (!mainActivity.isAppBarClosed()) {
                    adjustheight();
                    if (Objects.requireNonNull(MainActivity.Companion.getMNestedView())
                            .getVisibility() == VISIBLE)
                        LiveDataBus.get().with("msgEvent").setValue(
                                new MessageEvent(new LocalDate(myPagerAdapter.monthModels.get(position).getYear(),
                                        myPagerAdapter.monthModels.get(position).getMonth(), 1),
                                        -1, Color.parseColor(Tool.color)));
                    else {
                        MainActivity.Companion.setLastdate(
                                new LocalDate(myPagerAdapter.monthModels.get(position).getYear(), myPagerAdapter.monthModels.get(position).getMonth(), 1));
                    }

                    updategrid();
                    //     myPagerAdapter.getFirstFragments().get(position).updategrid();
                    // myPagerAdapter.notifyDataSetChanged();

                    if (monthChangeListner != null)
                        monthChangeListner.onMonthChange(myPagerAdapter.monthModels.get(position));
                }
            }
        });
        var indexTrack = new ArrayList<EventPositionBean>();
        int i = 0;
        ArrayList<EventModel> eventModels = new ArrayList<>();
        for (EventListBean eventModel : eventhash) {
            EventInfo tempInfo = eventModel.getEvent();
            String s = "";
            int type = 0;
            if(tempInfo.eventtitles!=null&&tempInfo.eventtitles.length>0){
                s= tempInfo.eventtitles[0];
            }
            if (s.startsWith("today")) type = 2;
            else if (s.equals("start")) type = 1;
            else if (s.startsWith("weekView")) type = 3;
            String ss = s;
            int color = mDefaultEventColor;
            if (type == 0) {
                color = tempInfo.eventcolor;
                if (tempInfo.noofdayevent > 1&& !Objects.equals(tempInfo.accountname, "holiday")) {
                    ss = ss + " (" + eventModel.getData().toString("d MMMM") + "-" +
                            eventModel.getData().plusDays(tempInfo.noofdayevent - 1).toString("d MMMM") + ")";
                } else if (!tempInfo.isallday) {
                    String start = DateExtensionKt.format(tempInfo.starttime, DateExtensionKt.PATTERN_HOUR_MINUTE);
                    String end = DateExtensionKt.format(tempInfo.endtime, DateExtensionKt.PATTERN_HOUR_MINUTE);
                    ss = ss + " (" + start + "-" + end + ")";
                }
                if(eventModel.getEvent().address!=null){
                    ss = ss + " " + eventModel.getEvent().address;
                }
            }

            EventModel mModel = new EventModel(ss, eventModel.getData(), type, color, tempInfo.id);
            if (!eventModels.contains(mModel)) {
                eventModels.add(mModel);
            }
            indexTrack.add(new EventPositionBean(eventModel.getData(), i));
            i++;
        }
        LiveDataBus.get().with("addEvent").setValue(new AddEvent(eventModels, indexTrack, arrayList));
    }

    public void updategrid() {
        final MonthPagerAdapter myPagerAdapter = (MonthPagerAdapter) viewPager.getAdapter();
        if (myPagerAdapter != null) {
            final int position = viewPager.getCurrentItem();
            // myPagerAdapter.getFirstFragments().get(position).updategrid();
            RecyclerView recyclerView = (RecyclerView) viewPager.getChildAt(0);


            MonthPagerAdapter.MonthViewHolder monthViewHolder = (MonthPagerAdapter.MonthViewHolder) recyclerView.findViewHolderForAdapterPosition(position);
            if (monthViewHolder != null && monthViewHolder.jCalendarMonthTopView != null) {

                monthViewHolder.jCalendarMonthTopView.requestLayout();
                monthViewHolder.jCalendarMonthTopView.invalidate();

            }
        }
    }

    public void adjustheight() {
        if (mindate == null) return;
        final MonthPagerAdapter myPagerAdapter = (MonthPagerAdapter) viewPager.getAdapter();
        if (myPagerAdapter != null) {
            final int position = viewPager.getCurrentItem();
            int size = myPagerAdapter.monthModels.get(position).getDayModelArrayList().size() + myPagerAdapter.monthModels.get(position).getFirstday();
            int numbercolumn = size % 7 == 0 ? size / 7 : (size / 7) + 1;
            ViewGroup.LayoutParams params = getLayoutParams();
            int setheight = 75 + (context.getResources().getDimensionPixelSize(R.dimen.itemheight) * numbercolumn) + context.getResources().getDimensionPixelSize(R.dimen.tendp) + getStatusBarHeight();
            if (params.height == setheight) return;
            params.height = setheight;
            // params.height=0;//jigs change
            setLayoutParams(params);


        }

    }

    public int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

//    public class MyPagerAdapter extends FragmentStatePagerAdapter {
//        private ArrayList<MonthModel> monthModels;
//        private ArrayList<FirstFragment> firstFragments = new ArrayList<>();
//
//        public MyPagerAdapter(FragmentManager fragmentManager, ArrayList<MonthModel> monthModels) {
//
//            super(fragmentManager);
//            this.monthModels = monthModels;
//            for (int i = 0; i < monthModels.size(); i++) {
//                firstFragments.add(FirstFragment.newInstance(monthModels.get(i).getMonth(), monthModels.get(i).getYear(), monthModels.get(i).getFirstday(), monthModels.get(i).getDayModelArrayList()));
//            }
//        }
//
//        public ArrayList<MonthModel> getMonthModels() {
//            return monthModels;
//        }
//
//        public ArrayList<FirstFragment> getFirstFragments() {
//            return firstFragments;
//        }
//
//        // Returns total number of pages
//        @Override
//        public int getCount() {
//            return monthModels.size();
//        }
//
//
//        // Returns the fragment to display for that page
//        @Override
//        public Fragment getItem(int position) {
//
//            return firstFragments.get(position);
//
//        }
//    }

    class MonthPagerAdapter extends RecyclerView.Adapter<MonthPagerAdapter.MonthViewHolder> {

        private ArrayList<MonthModel> monthModels;
        private LayoutInflater mInflater;
        private Context context;

        MonthPagerAdapter(Context context, ArrayList<MonthModel> data) {
            this.context = context;
            this.mInflater = LayoutInflater.from(context);
            this.monthModels = data;
        }

        @NonNull
        @Override
        public MonthViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = mInflater.inflate(R.layout.fraglay, parent, false);
            return new MonthViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull MonthViewHolder holder, int position) {

            MonthModel monthtemp = monthModels.get(position);

            holder.jCalendarMonthTopView.initdata(monthtemp.getDayModelArrayList(), monthtemp.getFirstday(), monthtemp.getMonth(), monthtemp.getYear());
//            Dayadapter dayadapter = new Dayadapter(context, monthtemp.getDayModelArrayList(), monthtemp.getFirstday(), monthtemp.getMonth(), monthtemp.getYear());
//            holder.gridview.setAdapter(dayadapter);
//            dayadapter.notifyDataSetChanged();


        }

        @Override
        public int getItemCount() {
            return monthModels.size();
        }


        class MonthViewHolder extends RecyclerView.ViewHolder {

            // RecyclerView gridview;
            JCalendarMonthTopView jCalendarMonthTopView;

            MonthViewHolder(View itemView) {
                super(itemView);
                jCalendarMonthTopView = itemView.findViewById(R.id.jcalendarmonthview);


            }
        }
    }

    class Dayadapter extends RecyclerView.Adapter<Dayadapter.DayViewHolder> {

        private ArrayList<DayModel> dayModels;
        private LayoutInflater mInflater;
        private int firstday;
        private int month, year;


        public Dayadapter(Context context, ArrayList<DayModel> dayModels, int firstday, int month, int year) {
            this.mInflater = LayoutInflater.from(context);
            this.dayModels = dayModels;
            this.firstday = firstday;
            this.month = month;
            this.year = year;
        }

        @Override
        public DayViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            View view = mInflater.inflate(R.layout.gridlay, parent, false);
            return new DayViewHolder(view);

        }


        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(DayViewHolder holder, int position) {


            if (position >= firstday) {
                position = position - firstday;
                DayModel dayModel = dayModels.get(position);
                LocalDate date = MainActivity.Companion.getLastdate();
                boolean selected = dayModel.getDay() == date.getDayOfMonth()
                        && dayModel.getMonth() == date.getMonthOfYear()
                        && dayModel.getYear() == date.getYear();

                if (dayModel.isToday()) {
                    holder.textView.setBackgroundResource(R.drawable.circle);
                    holder.textView.setTextColor(Color.WHITE);

                } else if (selected) {
                    holder.textView.setBackgroundResource(R.drawable.selectedback);
                    holder.textView.setTextColor(Color.rgb(91, 128, 231));

                } else {
                    holder.textView.setBackgroundColor(Color.TRANSPARENT);
                    holder.textView.setTextColor(Color.rgb(80, 80, 80));

                }
                holder.textView.setText(String.valueOf(dayModels.get(position).getDay()));

                if (dayModel.getEventlist() && !selected) {
                    holder.eventview.setVisibility(View.VISIBLE);
                } else {
                    holder.eventview.setVisibility(View.GONE);
                }
            } else {
                holder.textView.setBackgroundColor(Color.TRANSPARENT);
                holder.textView.setText("");
                holder.eventview.setVisibility(View.GONE);
            }


        }

        @Override
        public int getItemCount() {

            return dayModels.size() + firstday;
        }

        class DayViewHolder extends RecyclerView.ViewHolder {

            private TextView textView;
            private View eventview;

            @SuppressLint("NotifyDataSetChanged")
            public DayViewHolder(View itemView) {
                super(itemView);
                textView = itemView.findViewById(R.id.textView8);
                eventview = itemView.findViewById(R.id.eventview);
                itemView.setOnClickListener(view -> {
                    if (getAdapterPosition() >= firstday) {
                        for (DayModel dayModel : dayModels) {
                            dayModel.setSelected(false);
                        }

                        LocalDate date = MainActivity.Companion.getLastdate();
                        MainActivity.Companion.setLastdate(new LocalDate(year, month, dayModels.get(getAdapterPosition() - firstday).getDay()));
                        if (Objects.requireNonNull(MainActivity.Companion.getMNestedView()).getVisibility() == VISIBLE)
                            LiveDataBus.get().with("msgEvent").setValue(new MessageEvent(
                                    new LocalDate(year, month, dayModels.get(getAdapterPosition() - firstday).getDay()),
                                    -1, Color.parseColor(Tool.color)));
                        // dayModels.get(getAdapterPosition()-firstday).setSelected(true);
                        if (Objects.requireNonNull(MainActivity.Companion.getWeekviewcontainer()).getVisibility() == VISIBLE) {
                            Calendar todaydate = Calendar.getInstance();
                            todaydate.set(Calendar.DAY_OF_MONTH, date.getDayOfMonth());
                            todaydate.set(Calendar.MONTH, date.getMonthOfYear() - 1);
                            todaydate.set(Calendar.YEAR, date.getYear());
                            MainActivity.Companion.getMWeekView().goToDate(todaydate);
                        }
                        notifyDataSetChanged();
                    }

                });
            }
        }
    }
}
